package com.example;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author: wyp
 * @Date: 2021/9/8 23:06
 * 解决ABA问题
 */
public class AtomicStampedReferenceDemo {

    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(10, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t 当前版本号：" + stamp);
            //线程睡眠，让B线程获取到当前主内存的值
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicStampedReference.compareAndSet(10, 20, 1, 2) + "\t compareAndSet完成的值： \t " + atomicStampedReference.getReference().toString());
            System.out.println(atomicStampedReference.compareAndSet(20, 10, 2, 3) + "\t compareAndSet完成的值： \t " + atomicStampedReference.getReference().toString());
        }, "A").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t 当前版本号：" + stamp);
            //线程睡眠，让A线程完成更新操作
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicStampedReference.compareAndSet(10, 20, 1, 2) + "\t compareAndSet完成的值： \t " + atomicStampedReference.getReference().toString());
        }, "B").start();
    }
}